package com.ty.zls.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;

import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.ty.zls.MainActivity;
import com.ty.zls.R;
import com.ty.zls.bean.Constants;
import com.ty.zls.util.CommonUtil;
import com.ty.zls.util.HttpUtil;
import com.ty.zls.util.StringUtils;
import com.ty.zls.util.StrogeUtil;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.CheckVersionResult;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.proxy.IUpdateHttpService;
import com.xuexiang.xupdate.proxy.IUpdateParser;
import com.xuexiang.xupdate.proxy.IUpdateProxy;
import com.xuexiang.xupdate.proxy.impl.AbstractUpdateProxy;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateChecker;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateParser;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xupdate.utils.UpdateUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class FlashActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        QMUIStatusBarHelper.translucent(this);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);


    }

    @Override
    protected void onStart() {
        super.onStart();
        XUpdate.newBuild(FlashActivity.this)
                .updateUrl(HttpUtil.CHECK_VERSION)
                .isAutoMode(false)
                .updateParser(new IUpdateParser() {
                    @Override
                    public UpdateEntity parseJson(String json) throws Exception {
                        if (!TextUtils.isEmpty(json)) {
                            CheckVersionResult checkResult = UpdateUtils.fromJson(json, CheckVersionResult.class);
                            if (checkResult != null && checkResult.getCode() == 0) {
                                checkResult = doLocalCompare(checkResult);

                                UpdateEntity updateEntity = new UpdateEntity();
                                if (checkResult.getUpdateStatus() == CheckVersionResult.NO_NEW_VERSION) {
                                    updateEntity.setHasUpdate(false);
                                    String token = StrogeUtil.getStringFraomPs(FlashActivity.this, StrogeUtil.user, StrogeUtil.token);
                                    if (StringUtils.isNotEmpty(token)) {
                                        Map<String, String> request = new HashMap<>();
                                        request.put("token", token);
                                        new MyTask().execute(request);
                                    } else {
                                        finish();
                                        startActivity(new Intent(FlashActivity.this, LoginActivity.class));
                                    }
                                } else {
                                    if (checkResult.getUpdateStatus() == CheckVersionResult.HAVE_NEW_VERSION_FORCED_UPLOAD) {
                                        updateEntity.setForce(true);
                                    }
                                    updateEntity.setHasUpdate(true)
                                            .setUpdateContent(checkResult.getModifyContent())
                                            .setVersionCode(checkResult.getVersionCode())
                                            .setVersionName(checkResult.getVersionName())
                                            .setDownloadUrl(checkResult.getDownloadUrl())
                                            .setSize(checkResult.getApkSize())
                                            .setMd5(checkResult.getApkMd5());
                                }
                                return updateEntity;

                            }
                        }
                        return null;
                    }

                    /**
                     * 进行本地版本判断[防止服务端出错，本来是不需要更新，但是服务端返回是需要更新]
                     *
                     * @param checkResult
                     * @return
                     */
                    private CheckVersionResult doLocalCompare(CheckVersionResult checkResult) {
                        if (checkResult.getUpdateStatus() != CheckVersionResult.NO_NEW_VERSION) { //服务端返回需要更新
                            int lastVersionCode = checkResult.getVersionCode();
                            if (lastVersionCode <= UpdateUtils.getVersionCode(XUpdate.getContext())) { //最新版本小于等于现在的版本，不需要更新
                                checkResult.setRequireUpgrade(CheckVersionResult.NO_NEW_VERSION);
                            }
                        }
                        return checkResult;
                    }
                })
                .update();
    }

    class MyTask extends AsyncTask<Map<String, String>, Void, Map<String, Object>> {
        @Override
        protected Map<String, Object> doInBackground(Map<String, String>... maps) {
            Map<String, Object> data = new HashMap<>();
            try {
                JSONObject result = HttpUtil.post(maps[0], HttpUtil.VALIDATE);
                int code = result.optInt("code");
                data.put("code", code);
                data.put("msg", result.optString("msg"));
                data.put("user", result.optJSONObject("user"));
            } catch (Exception e) {
                data.put("code", Constants.ERROR_CODE);
            }
            return data;
        }

        @Override
        protected void onPostExecute(Map<String, Object> map) {
            super.onPostExecute(map);
            String title = "";
            final Integer code = (Integer) map.get("code");
            if (Constants.ERROR_CODE.equals(code)) {
                if (!CommonUtil.isNetworkAvailable(FlashActivity.this)) {
                    title = "发送失败,请检查网络是否连接";
                } else {
                    title = "发送失败,请稍后重试";
                }
                 new QMUITipDialog.Builder(FlashActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord(title)
                        .create().show();
            } else if (Constants.FAIL_CODE.equals(code)) {
                new QMUITipDialog.Builder(FlashActivity.this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord((String) map.get("msg"))
                        .create().show();
            } else if (Constants.SUCCESS_CODE.equals(code)) {
                finish();
                if (map.get("user") != null) {
                    startActivity(new Intent(FlashActivity.this, MainActivity.class));
                } else {
                    startActivity(new Intent(FlashActivity.this, LoginActivity.class));
                }
            }
        }
    }
}
